package com.meida.module.marketing.provider.service.impl;

import com.meida.common.constants.CommonConstants;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.module.marketing.client.entity.MkgCoupon;
import com.meida.module.marketing.client.entity.MkgCouponUser;
import com.meida.module.marketing.provider.mapper.CouponUserMapper;
import com.meida.module.marketing.provider.service.CouponUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 实现类
 *
 * @author flyme
 * @date 2019-10-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CouponUserServiceImpl extends BaseServiceImpl<CouponUserMapper, MkgCouponUser> implements CouponUserService {


    @Override
    public ResultBody beforePageList(CriteriaQuery<MkgCouponUser> cq, MkgCouponUser mkgCouponUser, EntityMap requestMap) {
        Long userId = OpenHelper.getUserId();
        cq.select(MkgCouponUser.class, "userId","useState","useTime");
        cq.select(MkgCoupon.class, "*");
        cq.eq(MkgCoupon.class, "state", CommonConstants.ENABLED);
        cq.eq(MkgCouponUser.class, "userId", userId);
        cq.createJoin(MkgCoupon.class);
        cq.groupBy("couponPrice");
        return ResultBody.ok();
    }


    @Override
    public ResultBody beforeGet(CriteriaQuery<MkgCouponUser> cq, MkgCouponUser mkgCouponUser, EntityMap requestMap) {
        Long userId = OpenHelper.getUserId();
        ApiAssert.isNotEmpty("请先登录", userId);
        Long couponId = requestMap.getLong("couponId");
        ApiAssert.isNotEmpty("优惠券Id不能为空", couponId);
        cq.select(MkgCoupon.class, "*");
        cq.eq(true, "couponId", couponId);
        cq.eq(true, "userId", userId);
        return ResultBody.ok();
    }


    @Override
    public EntityMap getCoupon(Long couponId) {
        CriteriaQuery cq = new CriteriaQuery(MkgCouponUser.class);
        Long userId = OpenHelper.getUserId();
        ApiAssert.isNotEmpty("请先登录", userId);
        ApiAssert.isNotEmpty("优惠券Id不能为空", couponId);
        cq.select(MkgCoupon.class, "*");
        cq.eq(true, "couponId", couponId);
        cq.eq(true, "userId", userId);
        return findOne(cq);
    }
}
